var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
define(["require", "exports", "N/ui/serverWidget", "N/log", "N/search", "N/file", "./YLES_RELATED_RECORDTYPE"], function (require, exports, serverWidget_1, log, search, file, YLES_RELATED_RECORDTYPE_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createImportResultForm = exports.createUI = void 0;
    serverWidget_1 = __importDefault(serverWidget_1);
    //创建Get界面的Form
    /**
     *
     * @param UI_GET_INFO - 封装的Form信息
     * @param sublistType - 创建的子列表的类型 ，默认为LIST
     * @param needMarkBtn - 是否需要添加markAll按钮，默认添加
     * @param hideNavBar - Form 是否需要隐藏NS菜单
     */
    function createUI(UI_GET_INFO, sublistType = serverWidget_1.default.SublistType.LIST, needMarkBtn = true, hideNavBar = false) {
        const form = serverWidget_1.default.createForm({ title: UI_GET_INFO.title, hideNavBar: hideNavBar });
        //btn
        for (const bv of UI_GET_INFO.btn) {
            form.addButton(bv);
        }
        //group
        for (const gv of UI_GET_INFO.group) {
            form.addFieldGroup(gv);
        }
        //tab
        if (UI_GET_INFO.tab) {
            for (const tv of UI_GET_INFO.tab) {
                form.addFieldGroup(tv);
            }
        }
        //body field
        for (const bfv of UI_GET_INFO.bodyField) {
            form.addField(bfv);
            if (bfv.isMandatory)
                form.getField({ id: bfv.id }).isMandatory = bfv.isMandatory;
            if (bfv.displayType) {
                form.getField({ id: bfv.id }).updateDisplayType({ displayType: bfv.displayType });
            }
            if (bfv.breakType) {
                form.getField({ id: bfv.id }).updateBreakType({ breakType: bfv.breakType });
            }
        }
        //line field
        if (sublistType && UI_GET_INFO.lineField.length > 0) {
            const sublist = form.addSublist({ id: 'info_list', label: 'Results', type: sublistType });
            for (const lfv of UI_GET_INFO.lineField) {
                sublist.addField(lfv);
                if (lfv.displayType) {
                    sublist.getField({ id: lfv.id }).updateDisplayType({ displayType: lfv.displayType });
                }
            }
            //mark all button
            if (needMarkBtn) {
                sublist.addButton({ id: 'mark_all', label: 'Mark All', functionName: 'markAll(true)' });
                sublist.addButton({ id: 'unmark_all', label: 'Unmark All', functionName: 'markAll(false)' });
                sublist.addButton({ id: 'mark100', label: 'Mark 100', functionName: 'markAll(true,100)' });
            }
            if (form.getField({ id: 'lines_page' })) {
                addCustomSource(form.getField({ id: 'lines_page' }), ['10', '50', '100', '200', '500', '1000']);
            }
        }
        //more sublist
        if (UI_GET_INFO.sublistInfo) {
            //添加多个sublist
            for (const sl of UI_GET_INFO.sublistInfo.sublist) {
                const sublist = form.addSublist({ id: sl.id, label: sl.label, type: sl.type, tab: sl.tab });
                //每个sublist的字段
                for (const slf of UI_GET_INFO.sublistInfo[sl.id]) {
                    sublist.addField(slf);
                    if (slf.displayType) {
                        sublist.getField({ id: slf.id }).updateDisplayType({ displayType: slf.displayType });
                    }
                }
            }
        }
        return form;
    }
    exports.createUI = createUI;
    //添加自定义select source
    function addCustomSource(f, source) {
        for (const d of source) {
            if (typeof d === 'string') {
                f.addSelectOption({ value: d, text: d });
            }
            else {
                f.addSelectOption(d);
            }
        }
    }
    //获取导入信息
    function getImportLogInfo(logId) {
        const columns = ['custrecord_yles_csv_name', 'custrecord_yles_status', 'custrecord_yles_start_time', 'custrecord_yles_end_time',
            'custrecord_yles_csvfile', 'custrecord_yles_ck_error_csv', 'custrecord_yles_imp_error_csv', 'custrecord_yles_imp_csv_line_no',
            'custrecord_yles_total_csv_line_no', 'custrecord_yles_ckd_line_no'];
        const res = search.lookupFields({ type: (0, YLES_RELATED_RECORDTYPE_1.CustomRecordType)().IMPORT_ITEM_BARCODE_LOG, id: logId, columns: columns });
        const logInfo = {};
        log.debug('res', res);
        logInfo.fileName = res[columns[0]];
        logInfo.state = (res[columns[1]][0] || {}).text;
        logInfo.stateid = (res[columns[1]][0] || {}).value;
        logInfo.created = res[columns[2]];
        logInfo.completedTime = res[columns[3]];
        logInfo.csvFile = (res[columns[4]][0] || {}).value;
        logInfo.ckErrorFile = (res[columns[5]][0] || {}).value;
        logInfo.impErrorFile = (res[columns[6]][0] || {}).value;
        logInfo.ckSuccessLine = res[columns[7]];
        logInfo.totalLine = res[columns[8]];
        logInfo.ckdLine = res[columns[9]];
        return logInfo;
    }
    //创建导入历史界面
    function createImportResultForm(logId, irForm) {
        const importLogInfo = getImportLogInfo(logId);
        log.debug('importLogInfo', importLogInfo);
        irForm.addFieldGroup({ id: 'result_group', label: 'Result' });
        let ff = irForm.addField({ id: 'file', label: 'Imported CSV File', type: 'inlinehtml', container: 'result_group' });
        ff.updateDisplayType({ displayType: 'inline' });
        // ff.defaultValue = importLogInfo.csvFile as string;
        ff.defaultValue = spellFileHtml('file', 'Imported CSV File', importLogInfo.csvFile, importLogInfo.fileName);
        let cf = irForm.addField({ id: 'created', label: 'Created Time', type: 'text', container: 'result_group' });
        cf.updateDisplayType({ displayType: 'inline' });
        cf.defaultValue = importLogInfo.created;
        let cdf = irForm.addField({ id: 'completed_time', label: 'Completed Time', type: 'text', container: 'result_group' });
        cdf.updateDisplayType({ displayType: 'inline' });
        cdf.defaultValue = importLogInfo.completedTime;
        let sf = irForm.addField({ id: 'state', label: 'Status', type: 'text', container: 'result_group' });
        sf.updateDisplayType({ displayType: 'inline' });
        sf.defaultValue = importLogInfo.state;
        let lgf = irForm.addField({ id: 'import_log_id', label: 'Log', type: 'text', container: 'result_group' });
        lgf.updateDisplayType({ displayType: 'hidden' });
        lgf.defaultValue = String(logId);
        let csf = irForm.addField({ id: 'ck_success_line', label: 'Check Success Line', type: 'text', container: 'result_group' });
        csf.updateDisplayType({ displayType: 'hidden' });
        csf.defaultValue = String(importLogInfo.ckSuccessLine || '');
        //添加报错文件
        let cef = irForm.addField({ id: 'ck_error_file', label: 'Check Error File', type: 'inlinehtml', container: 'result_group' });
        cef.updateDisplayType({ displayType: 'inline' });
        // cef.defaultValue = importLogInfo.ckErrorFile as string;
        cef.defaultValue = spellFileHtml('ck_error_file', 'Check Error File', importLogInfo.ckErrorFile, 'Check Error File');
        let ief = irForm.addField({ id: 'imp_error_file', label: 'Import Error File', type: 'inlinehtml', container: 'result_group' });
        ief.updateDisplayType({ displayType: 'inline' });
        // ief.defaultValue = importLogInfo.impErrorFile as string;
        ief.defaultValue = spellFileHtml('imp_error_file', 'Import Error File', importLogInfo.impErrorFile, 'Import Error File');
        //导入进度条
        if (importLogInfo.stateid == '3') {
            let ipf = irForm.addField({ id: 'progress', label: 'progress', type: 'inlinehtml', container: 'result_group' });
            ipf.updateDisplayType({ displayType: 'inline' });
            ipf.defaultValue = `
                <div><br/><br/><br/><br/><br/><table>
                <tr><td style="font-size: 15px">Import Progress： &nbsp;</td></tr>
                <tr><td><div style="width: 450px" id="import_csv_progress" data-init="true"></div></td></tr>
                </table></div>
            `;
            addExternalJS(irForm);
        }
        //校验进度
        else if (importLogInfo.stateid == '2') {
            irForm.title = 'Check Item&Barcode';
            let tsf = irForm.addField({ id: 'total_line', label: 'Total Line', type: 'text', container: 'result_group' });
            tsf.updateDisplayType({ displayType: 'hidden' });
            tsf.defaultValue = String(importLogInfo.totalLine || '');
            let tff = irForm.addField({ id: 'ckd_line', label: 'Checked Line', type: 'text', container: 'result_group' });
            tff.updateDisplayType({ displayType: 'hidden' });
            tff.defaultValue = String(importLogInfo.ckdLine || '');
            let ipf = irForm.addField({ id: 'progress', label: 'progress', type: 'inlinehtml', container: 'result_group' });
            ipf.updateDisplayType({ displayType: 'inline' });
            ipf.defaultValue = `
                <div><br/><br/><br/><br/><br/><table>
                <tr><td style="font-size: 15px">Check Progress： &nbsp;</td></tr>
                <tr><td><div style="width: 450px" id="check_csv_progress" data-init="true"></div></td></tr>
                </table></div>
            `;
            addExternalJS(irForm);
        }
        irForm.addButton({ id: 'refresh', label: 'Refresh', functionName: 'refresh' });
    }
    exports.createImportResultForm = createImportResultForm;
    //添加外部js
    function addExternalJS(form) {
        const js_file_obj = file.load({ id: './jquery.lineProgressbar.js' });
        const js_str = js_file_obj.getContents();
        const css_file_obj = file.load({ id: './jquery.lineProgressbar.css' });
        const css_str = css_file_obj.getContents();
        try {
            const tmpHtmlVal = `<script>
                    try{
                        ${js_str}
                    }catch (ex) {
                        console.log('addExternalJS error',ex);
                    };
                </script>

                <style type="text/css">
                    ${css_str}
                </style>`;
            form.addField({
                type: 'inlinehtml',
                label: ' &nbsp; ',
                id: 'custpage__add_external_js'
            }).defaultValue = tmpHtmlVal;
        }
        catch (ex) {
            log.error({
                title: 'addExternalJS error',
                details: ex
            });
        }
    }
    //拼写file的html代码
    function spellFileHtml(fid, fName, fileId, fileName) {
        if (fileId) {
            return `<div class="uir-field-wrapper" data-field-type="select">
        <span id="${fid}_fs_lbl_uir_label" class="smallgraytextnolink uir-label ">
        <span id="${fid}_fs_lbl" class="smallgraytextnolink" style="">
        <a tabindex="-1" title="What's this?" style="cursor:help" class="smallgraytextnolink">${fName}</a>
        </span></span><span class="uir-field inputreadonly">
        <a class="smalltext" href="#" style="text-decoration: none;" onclick="previewMedia(${fileId},false,true); return false" onmouseover="this.style.textDecoration='underline'; window.status='preview file'; return true;" onmouseout="this.style.textDecoration='none'; window.status='';">preview ${fileName}</a>&nbsp;&nbsp;
        <a href="#" onclick="previewMedia(${fileId},false,true); return false" class="smalltext">download</a>&nbsp;&nbsp;<a href="#" onclick="nlOpenWindow('/app/common/record/edittextmediaitem.nl?id=${fileId}&amp;e=T&amp;l=T&amp;target=filesize', 'edittextmediaitem${fileId}', 700, 880); return false" class="smalltext">Edit</a>
        </span>
    </div>`;
        }
        return `<div class="uir-field-wrapper" data-field-type="select"><span id="${fid}_fs_lbl_uir_label" class="smallgraytextnolink uir-label ">
            <span id="${fid}_fs_lbl" class="smallgraytextnolink" style="">
            <a tabindex="-1" title="What's this?" style="cursor:help" class="smallgraytextnolink">${fName}</a>
            </span></span><span class="uir-field inputreadonly">
            </span>
            </div>`;
    }
});
